package com.ywl.study.sharding.study06.config.precise;

import com.ywl.study.sharding.common.config.ExampleConfiguration;
import com.ywl.study.sharding.study03.util.DataSourceUtil;
import org.apache.shardingsphere.api.config.masterslave.MasterSlaveRuleConfiguration;
import org.apache.shardingsphere.shardingjdbc.api.MasterSlaveDataSourceFactory;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * 主从配置
 */
public class MasterSlaveConfiguration implements ExampleConfiguration {
    @Override
    public DataSource getDataSource() throws SQLException {
        MasterSlaveRuleConfiguration masterSlaveRuleConfig = new MasterSlaveRuleConfiguration("demo_ds_master_slave", "demo_ds_master", Arrays.asList("demo_ds_slave_0", "demo_ds_slave_1"));

        return MasterSlaveDataSourceFactory.createDataSource(createDataSourceMap(),masterSlaveRuleConfig,new Properties());
    }

    private Map<String,DataSource> createDataSourceMap(){
        Map<String, DataSource> result = new HashMap<>();
        result.put("demo_ds_master", DataSourceUtil.createDataSource("demo_ds_master"));
        result.put("demo_ds_slave_0", DataSourceUtil.createDataSource("demo_ds_slave_0"));
        result.put("demo_ds_slave_1", DataSourceUtil.createDataSource("demo_ds_slave_1"));
        return result;
    }
}
